package com.smart.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.smart.constants.SmartConstants;
import com.smart.model.AccessToken;
import com.smart.model.inform.Filter;
import com.smart.model.inform.Text;
import com.smart.model.inform.TextFormat;
import com.smart.model.menu.Button;
import com.smart.model.menu.ClickButton;
import com.smart.model.menu.Menu;
import com.smart.model.menu.ViewButton;

import net.sf.json.JSONObject;

public class WeixinUtil {
	/**
	 * GET请求
	 * 
	 * @param getUrl
	 * @throws IOException
	 * @return 提取HTTP响应报文包体，以JSONObject形式返回
	 */
	public static JSONObject doGetStr(String getUrl) {
		String result = "";
		try {
			URL getURL = new URL(getUrl);
			HttpURLConnection connection = (HttpURLConnection) getURL.openConnection();
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.connect();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder sbStr = new StringBuilder();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				sbStr.append(line);
			}
			bufferedReader.close();
			connection.disconnect();
			result = new String(sbStr.toString().getBytes(), "utf-8");
			System.out.println("result:" + result);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(result);
		return jsonObject;
	}

	public static JSONObject doGetStr2(String url) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		JSONObject jsonObject = null;
		try {
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String result = EntityUtils.toString(entity, "UTF-8");
				jsonObject = JSONObject.fromObject(result);
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObject;
	}

	/**
	 * POST请求 ,解决中文乱码问题
	 * 
	 * @param postUrl
	 * @param postHeaders
	 * @param postEntity
	 * @throws IOException
	 * @return 提取HTTP响应报文包体，以JSONObject形式返回
	 */
	public static JSONObject doPostStr(String postUrl, String postEntity) {
		String result = "";
		try {
			URL postURL = new URL(postUrl);
			System.out.println("postURL:" + postURL);
			HttpURLConnection httpURLConnection = (HttpURLConnection) postURL.openConnection();
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setInstanceFollowRedirects(true);
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			if (postEntity != null) {
				PrintWriter out = new PrintWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "utf-8"));
				out.println(postEntity);
				out.flush();
				out.close();
			}
			// connection.connect();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(httpURLConnection.getInputStream()));
			StringBuilder sbStr = new StringBuilder();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				sbStr.append(line);
			}
			bufferedReader.close();
			httpURLConnection.disconnect();
			result = new String(sbStr.toString().getBytes(), "utf-8");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return JSONObject.fromObject(result);
	}

	/**
	 * POST请求
	 * 
	 * @param postUrl
	 * @param postHeaders
	 * @param postEntity
	 * @throws IOException
	 * @return 提取HTTP响应报文包体，以JSONObject形式返回
	 */
	public static JSONObject doPostStr2(String postUrl, String postEntity) throws IOException {

		String result = "";
		try {
			URL postURL = new URL(postUrl);
			System.out.println("postURL:" + postURL);
			HttpURLConnection httpURLConnection = (HttpURLConnection) postURL.openConnection();
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setInstanceFollowRedirects(true);
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			if (postEntity != null) {
				DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
				out.writeBytes(postEntity);
				out.flush();
				out.close(); // flush and close
			}
			// connection.connect();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(httpURLConnection.getInputStream()));
			StringBuilder sbStr = new StringBuilder();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				sbStr.append(line);
			}
			bufferedReader.close();
			httpURLConnection.disconnect();
			result = new String(sbStr.toString().getBytes(), "utf-8");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return JSONObject.fromObject(result);
	}

	public static AccessToken getAccessToken() {
		return AccessTokenManager.getAccessToken();
	}

	public static String genarateAuthorizeUrl(String redirect_uri) {
		// String
		// reg_url="http://www.smartcommunity.site/InformationTest/user_inform";
		String encode_url = null;
		try {
			encode_url = URLEncoder.encode(redirect_uri, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String authorize_url = SmartConstants.AUTHORIZE_URL.replace("APPID", SmartConstants.APPID)
				.replace("REDIRECT_URI", encode_url).replace("SCOPE", "snsapi_userinfo");
		return authorize_url;
	}

	public static void sendAll(String message) {
		AccessToken token = getAccessToken();
		String url = SmartConstants.SENDALL_URL.replace("ACCESS_TOKEN", token.getToken());
		Filter filter = new Filter();
		Text text = new Text();
		text.setContent(message);
		filter.setIs_to_all(true);
		TextFormat textFormat = new TextFormat();
		textFormat.setFilter(filter);
		textFormat.setMsgtype("text");
		textFormat.setText(text);
		String sendMessage = JSONObject.fromObject(textFormat).toString();
		System.out.println("sendMessage is " + sendMessage);
		JSONObject jsonObject = doPostStr(url, sendMessage);
		System.out.println(jsonObject);
	}

	/* 模版消息 */
	public static void sendTemplateMessage(AccessToken token, String message) {
		String url = SmartConstants.TEMPLATE_MESSAGE.replace("ACCESS_TOKEN", token.getToken());
		JSONObject jsonObject = doPostStr(url, message);
		System.out.println(jsonObject);
	}

	/* 从微信服务器下载多媒体文件 */
	public static String downloadMediaFromWx(String accessToken, String mediaId, String fileSavePath)
			throws IOException {
		if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(mediaId))
			return null;

		String requestUrl = SmartConstants.WECHAT_MEDIA_DOWNLOAD_URL.replace("ACCESS_TOKEN", accessToken)
				.replace("MEDIA_ID", mediaId);
		System.out.println("media url == " + requestUrl);
		URL url = new URL(requestUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setDoInput(true);
		conn.setDoOutput(true);
		InputStream in = conn.getInputStream();

		File dir = new File(fileSavePath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		if (!fileSavePath.endsWith("/")) {
			fileSavePath += "/";
		}

		String ContentDisposition = conn.getHeaderField("Content-disposition");
		String weixinServerFileName = ContentDisposition.substring(ContentDisposition.indexOf("filename") + 10,
				ContentDisposition.length() - 1);

		// fileSavePath += weixinServerFileName;
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileSavePath + weixinServerFileName));
		byte[] data = new byte[1024];
		int len = -1;

		while ((len = in.read(data)) != -1) {
			bos.write(data, 0, len);
		}

		bos.close();
		in.close();
		conn.disconnect();
		System.out.println("weixinServerFileName == " + weixinServerFileName);
		String[] splitedFileName = weixinServerFileName.split("\\.");
		System.out.println("splitedFileName == " + splitedFileName[0] + " " + splitedFileName[1]);
		if (splitedFileName[1].equals("amr")) {
			System.out.println("audio converting");
			String mp3FileName = splitedFileName[0] + ".mp3";
			System.out.println("mp3 filename == " + mp3FileName);
			convertToMp3(fileSavePath + weixinServerFileName, fileSavePath + mp3FileName);
			return mp3FileName;
		}

		return weixinServerFileName;
	}

	public static void convertToMp3(String amrFile, String mp3File) {
		Process process = null;
		try {
			File mp3 = new File(mp3File);
			if (mp3.exists()) {
				mp3.delete();
			}
			process = Runtime.getRuntime().exec("sox " + amrFile + " " + mp3File);
			process.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			process.destroy();
		}
	}
}
